package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
	@Autowired(required = false)
	private ApArticleMapper articleMapper;
	@Autowired(required = false)
	private ApArticleContentMapper apArticleContentMapper;
	@Autowired(required = false)
	private Configuration configuration;
	@Autowired(required = false)
	private FileStorageService fileStorageService;

	@Override
	@Async
	public void buildArticleToMinIO(ApArticle article, String content) {
		try {
			//1.获取模板
			Template template = configuration.getTemplate("article.ftl");
			//2.获取数据模型
			ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, article.getId()));
			Map dataMotel = new HashMap();
			dataMotel.put("content", JSONArray.parseArray(apArticleContent.getContent()));
			//3.生成静态文件
			StringWriter out = new StringWriter();
			template.process(dataMotel, out);
			//4.上传到minIO中
			InputStream is = new ByteArrayInputStream(out.toString().getBytes());
			String html = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", is);
			//5.修改ap_article中的static_url字段
			if (article != null) {
				article.setStaticUrl(html);
				articleMapper.updateById(article);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
